package com.gxa.servlet;

import com.alibaba.fastjson.JSON;
import com.gxa.entity.Community;
import com.gxa.service.CommunityService;
import com.gxa.service.impl.CommunityServiceImpl;
import com.gxa.utils.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/page/community/add")
public class CommunityAddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        Result result = new Result(0,"success",null);

        try {
            String cid = req.getParameter("cid");
            String cname = req.getParameter("cname");
            String address = req.getParameter("address");
            String area = req.getParameter("area");
            String creator = req.getParameter("creator");
            String managers = req.getParameter("managers");
            String createTime = req.getParameter("createTime");
            String remark = req.getParameter("remark");

            //将日期的字符串转换为日期的对象
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = null;
            try {
                date = sdf.parse(createTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            Community community = new Community(Integer.parseInt(cid),cname,address,Double.parseDouble(area),creator,managers,date,remark);

            CommunityService communityService = new CommunityServiceImpl();
            communityService.add(community);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(1);
            result.setMsg("保存失败");
        }finally {
            String jsonStr = JSON.toJSONString(result);
            out.print(jsonStr);
        }




    }
}
